//
//  BRInfoViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/27.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRInfoViewController.h"
#import "BRTopTitleTableViewCell.h"
#import "BRHeaderImgTableViewCell.h"
#import "BRTitleTableViewCell.h"
#import "BRAlertCustomView.h"
#import "BRPickerView.h"
#import "BRMChangePhoneViewController.h"
#import "BRBindAccountVC.h"

@interface BRInfoViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    
    QMUIButton *_sendBtn;
}
@property (nonatomic,strong) NSArray *lists;

@end

@implementation BRInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
    
    // 进入页面时获取最新用户信息
    [self requestUserInfo];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

#pragma mark - 获取用户信息
- (void)requestUserInfo {
    [BRUserManager requestUserCenterInfo:^{
        // 用户信息获取成功，刷新页面
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } faile:^{
        // 获取失败，使用缓存数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - request --
- (void)changeInfo:(NSDictionary *)infoDic succ:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [BRHud showHud];
    [[BRRequestManager shared] PUT:[BRAPI editUserInfo] params:infoDic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        
        // 使用新接口获取最新用户信息
        [BRUserManager requestUserCenterInfo:^{
            [self.tableView reloadData];
            [BRHud hidden];
            if (succ) {
                succ();
            }
        } faile:^{
            // 新接口失败，提示错误
            [BRHud hidden];
            [BRHud showTips:@"获取用户信息失败"];
            if (faile) {
                faile();
            }
        }];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hidden];
        if (faile) {
            faile();
        }
    }];
}

- (NSDictionary *)infoDefaultDic {
    
    // 使用 userId 或 userID（兼容新旧接口）
    NSString *userId = USERManager.userModel.userId ?: USERManager.userModel.userID ?: @"";
    NSInteger sex = USERManager.userModel.sex;
    
    return @{@"appleId":@"",
             @"birthday":@"",
             @"email":@"",
             @"facebookId":@"",
             @"googleId":@"",
             @"icon":@"",
             @"id":userId,
             @"nickname":@"",
             @"nickName":@"",  // 新接口可能使用 nickName
             @"sex":@(sex),
    };
}

- (void)getOtp:(NSDictionary *)dic sendBtn:(QMUIButton *)btn {
    [BRHud showHud];
    btn.enabled = NO;
    _sendBtn = btn;
    [[BRRequestManager shared] GET:[BRAPI verificationCode] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
//        [BrezzeTimeManage share].phone = [NSString stringWithFormat:@"%@%@",codeStr,self->_phoneTF.text];
        [BrezzeTimeManage addObjectIndateDic:kTimeKeyStr];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
        [BRHud hidden];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hidden];
        btn.enabled = YES;
        if (code == 21012) {
            btn.enabled = NO;
            [BRHud showTips:@"信息请求过多"];
        }
    }];
}

- (void)reqestSentToEmail:(NSString *)email succ:(void(^)(BOOL isSucc))statusBlock {
    
    [BRHud showInView:self.view];
    
    NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:[self infoDefaultDic]];
    
    dic[@"receiptEmail"] = email;
    
    [self changeInfo:dic succ:^{
        
        
        statusBlock(YES);
    } faile:^{
        statusBlock(NO);
    }];
   
    
}


#pragma mark - 监听
- (void)notificationDoit {
    
    if (!_sendBtn) return;
    
    _sendBtn.enabled = NO;
    if ([BrezzeTimeManage getimeIntervalBy:kTimeKeyStr wirhMax:kTimeMax] > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSInteger num = [BrezzeTimeManage getimeIntervalBy:kTimeKeyStr wirhMax:kTimeMax];
            NSString *str2 = [NSString stringWithFormat:@"%02lds",(long)num];
            [self->_sendBtn setTitle:str2 forState:(UIControlStateNormal)];
        });
    }else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self->_sendBtn.enabled = YES;
            
            [self->_sendBtn setTitle:Localized(@"Login_sentOTP") forState:(UIControlStateNormal)];
            [BrezzeTimeManage removeObjectKey:kTimeKeyStr];
            self->_sendBtn = nil;
        });
    }
    
}

#pragma mark - tableView Delegate --
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.row == 0) return 96;
    return 66;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BRUserModel * user = USERManager.userModel;
    if (user.apple || user.google) return self.lists.count + 1;
    return self.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    if (indexPath.row == self.lists.count) {
        BRTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRTitleTableViewCell"];
       
        cell.titleL.textColor = UIColor.qd_titleTextColor2;
        cell.rightImg.hidden = YES;
        cell.subTitleL.hidden = NO;
        cell.hasText = NO;
        BRUserModel * user = USERManager.userModel;
        NSString *str = @"";
        if (user.apple) str = Localized(@"info_appleLogin");
        if (user.google) str = Localized(@"info_googleLogin");
        
        cell.titleL.text = str;
        cell.subTitleL.text = Localized(@"info_authorized");
        cell.lineView.hidden = YES;
        return cell;
    }
    
    NSString *text =  self.lists[indexPath.row];
    
    BRTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRTitleTableViewCell"];
    
    // 处理标题显示
    if ([text isEqualToString:@"nickName"]) {
        cell.titleL.text = Localized(@"profile_nickName");
    } else {
        cell.titleL.text = text;
    }
    
    BOOL isOne = [text isEqualToString:Localized(@"menu_userID")];
    BOOL isPhoneNumber = [text isEqualToString:Localized(@"login_phoeNumber")];
    
    cell.hasText = isOne;
    // 用户ID和手机号都不显示右侧箭头（不允许编辑）
    cell.hasRImg = !isOne && !isPhoneNumber;
    cell.subTitleL.hidden = isOne;
    
    if ([text isEqualToString:Localized(@"menu_userID")]) {
        // 使用 userId 字段
        NSString *userId = USERManager.userModel.userId ?: USERManager.userModel.userID;
        if (userId && userId.length > 0) {
            NSInteger userIdInt = userId.integerValue;
            cell.textL.text = [NSString stringWithFormat:@"U%08ld", (long)userIdInt];
        } else {
            cell.textL.text = @"--";
        }
    } else if ([text isEqualToString:@"nickName"]) {
        // 显示昵称
        NSString *nickName = USERManager.userModel.nickName ?: USERManager.userModel.nickname ?: @"";
        cell.subTitleL.text = (nickName.length > 0) ? nickName : Localized(@"info_select");
    } else if ([text isEqualToString:Localized(@"profile_birthday")]) {
        NSString *str = USERManager.userModel.birthday;
        str = (str.length != 0) ? str : @"DD/MM/YYYY";
        cell.subTitleL.text = str;
    } else if ([text isEqualToString:Localized(@"profile_gender")]) {
        NSInteger sex = USERManager.userModel.sex;
        NSString *str = Localized(@"info_select");
        if (sex == 1) {
            str = Localized(@"profile_male");
        }else if (sex == 0) {
            str = Localized(@"profile_female");
        }else if (sex == 2) {
            str = Localized(@"profile_secret");
        }
        cell.subTitleL.text = str;
    } 
    /* 屏蔽邮箱相关
    else if ([text isEqualToString:Localized(@"login_email")]) {
        NSString *str = USERManager.userModel.email;
        str = (str.length != 0) ? str : @"xxx@xxx.com";
        cell.subTitleL.text = str;
        
    }else if ([text isEqualToString:Localized(@"profile_receiptEmail")]) {
        NSString *str = USERManager.userModel.receiptEmail;
        str = (str.length != 0) ? str : @"xxx@xxx.com";
        cell.subTitleL.text = str;
        
    }
    */
    else if ([text isEqualToString:Localized(@"login_phoeNumber")]) {
        // 使用 mobile 字段（新接口）
        NSString *mobile = USERManager.userModel.mobile ?: USERManager.userModel.phone ?: @"";
        // 优先使用 userModel 中的 countryCode，否则使用登录时的区号
        NSString *countryCode = nil;
        if (USERManager.userModel.countryCode > 0) {
            countryCode = [NSString stringWithFormat:@"%ld", (long)USERManager.userModel.countryCode];
        } else if (USERManager.loginCode.length > 0) {
            countryCode = USERManager.loginCode;
        } else {
            countryCode = @"84"; // 默认值
        }
        if (mobile.length > 0) {
            cell.subTitleL.text = [NSString stringWithFormat:@"+%@ %@", countryCode, mobile];
        } else {
            cell.subTitleL.text = @"--";
        }
       
    }
    
    BRUserModel * user = USERManager.userModel;
    if (user.apple || user.google) {
        cell.lineView.hidden = NO;
    }else {
        cell.lineView.hidden = indexPath.row == self.lists.count - 1;
    }
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.lists.count) {
        return;
    }
    [self didSelectWithTitle:self.lists[indexPath.row]];
}

- (void)didSelectWithTitle:(NSString *)title {
    
    if ([title isEqualToString:Localized(@"menu_userID")]) {
        return;
    }
    
    // 手机号不允许点击编辑
    if ([title isEqualToString:Localized(@"login_phoeNumber")]) {
        return;
    }
    
    // 处理昵称编辑
    if ([title isEqualToString:@"nickName"]) {
        WS(weakSelf);
        NSString *currentNickName = USERManager.userModel.nickName ?: USERManager.userModel.nickname ?: @"";
        BRAlertCustomView *alert = [[BRAlertCustomView alloc] initWithFrame:self.view.bounds type:0];
        alert.titleStr = Localized(@"profile_nickName");
        alert.textTF.placeholder = Localized(@"profile_enterNickName");
        alert.textTF.text = currentNickName;
        alert.textTF.maximumTextLength = 20;
        [alert setRightBtnTitle:Localized(@"home_confirm")];
        [self.view addSubview:alert];
        
        alert.alertBlock = ^(NSString * _Nonnull changeText, NSInteger index, void (^ _Nonnull hidd)(BOOL)) {
            if (changeText.length == 0) {
                [BRHud show:Localized(@"profile_enterNickName") inView:self.view];
                return;
            }
            
            // 使用新接口修改昵称
            NSString *userIdStr = USERManager.userModel.userId ?: USERManager.userModel.userID ?: @"";
            if (userIdStr.length == 0) {
                [BRHud show:@"用户ID不能为空" inView:weakSelf.view];
                hidd(NO);
                return;
            }
            
            NSInteger userId = userIdStr.integerValue;
            NSDictionary *params = @{
                @"userId": @(userId),
                @"nickname": changeText
            };
            
            [BRHud showHud];
            [[BRRequestManager shared] POSTWithFormData:[BRAPI editNickname] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
                // 修改成功后，获取最新用户信息并刷新
                [BRUserManager requestUserCenterInfo:^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableView reloadData];
                        [BRHud hidden];
                        hidd(YES);
                    });
                } faile:^{
                    // 即使获取用户信息失败，也认为修改成功（因为接口返回成功）
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [BRHud hidden];
                        [BRHud showTips:@"修改成功，但获取最新信息失败"];
                        hidd(YES);
                    });
                }];
            } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [BRHud hidden];
                    [BRHud showTips:errMsg ?: @"修改昵称失败"];
                    hidd(NO);
                });
            }];
        };
        return;
    }
    
    if ([title isEqualToString:Localized(@"profile_gender")]) {
        
        WS(weakSelf);
        [self alertDo:title contentStr:@"" type:1 action:^(NSString * _Nonnull changeText, NSInteger index, void (^ _Nonnull hidd)(BOOL)) {
            //修改性别
            NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:[weakSelf infoDefaultDic]];
            NSInteger sex  = index;
            if (index == 0) {
                sex = 1;
            }
            if (index == 1) {
                sex = 0;
            }
            dic[@"sex"] = @(sex);
            
            [weakSelf changeInfo:dic succ:^{
                
            } faile:^{
                
            }];
            hidd(YES);
        }];
    }
    
    if ([title isEqualToString:Localized(@"profile_birthday")]) {
        
        [self showPickView];
        return;
    }
    /* 屏蔽邮箱相关功能
    if ([title isEqualToString:Localized(@"login_email")]) {
        
//        WS(weakSelf);
        NSString *str = USERManager.userModel.email;
        if (str.length != 0) {
            // 更换邮箱
            
            BRMChangePhoneViewController *vc = [[BRMChangePhoneViewController alloc] init];
            vc.isEmail = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }
        BRBindAccountVC *vc = [[BRBindAccountVC alloc] init];
        vc.isEmail = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    if ([title isEqualToString:Localized(@"profile_receiptEmail")]) {
        
        WS(weakSelf);
        NSString *str = USERManager.userModel.receiptEmail;
        if (str.length == 0) str = @"xxx@xxx.com";
        BRAlertCustomView *alert = [[BRAlertCustomView alloc] initWithFrame:self.view.bounds type:0];
        alert.titleStr = Localized(@"profile_emailReceiving");
        
        alert.textTF.placeholder = Localized(@"toast_requiredEmail");
        alert.textTF.maximumTextLength = 320;
        NSString *emailStr = USERManager.userModel.receiptEmail;
        alert.textTF.text = emailStr.length != 0 ? emailStr : @"";
        alert.textTF.keyboardType = UIKeyboardTypeEmailAddress;
        [alert setRightBtnTitle:Localized(@"home_confirm")];
        [self.view addSubview:alert];
        alert.alertBlock = ^(NSString * _Nonnull changeText, NSInteger index, void (^ _Nonnull hidd)(BOOL)) {
            
            if (changeText.length == 0) {
                [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
                return;
            }
            if (![BRTools checkEmail:changeText]) {
                [BRHud showAuto:Localized(@"toast_validEmail") inView:self.view];
                return;
            }
            //----
            [weakSelf reqestSentToEmail:changeText succ:^(BOOL isSucc) {
                hidd(isSucc);
            }];
        };
        
        return;
    }
    */
    if ([title isEqualToString:Localized(@"login_phoeNumber")]) {
        
        // 使用 mobile 字段（新接口）
        NSString *str = USERManager.userModel.mobile ?: USERManager.userModel.phone;
        if (str.length != 0)  {
            
            BRMChangePhoneViewController *vc = [[BRMChangePhoneViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }
        
        BRBindAccountVC *vc = [[BRBindAccountVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    if ([title isEqualToString:@"headerImg"]) {
        
        [self showSelectPhoto];
        
        
        return;
    }
    
    
}

- (BRAlertCustomView *)alertDo:(NSString *)title contentStr:(NSString *)contentStr type:(NSInteger)type action:(AlertBlcok)acBlock {
    
    BRAlertCustomView *alert = [[BRAlertCustomView alloc] initWithFrame:self.view.bounds type:type];
    alert.titleStr = title;
    
    if (type == 1) {
        NSArray *titles = @[Localized(@"profile_male"),Localized(@"profile_female"),Localized(@"profile_secret")];
        NSInteger sex = USERManager.userModel.sex;
        [alert setRightBtnTitle:Localized(@"home_confirm")];
        if (sex == 1) {
            alert.selIndex = 0;
        }else if (sex == 0) {
            alert.selIndex = 1;
        }else if (sex == 2) {
            alert.selIndex = 2;
        }
        
        alert.listArr = titles;
    }
    if (type == 0) {
        alert.textTF.placeholder = title;
        if ([title isEqualToString:Localized(@"Info_userID")]) {
            alert.textTF.placeholder = Localized(@"Info_enterNickName");
        }
        
    }
    alert.textTF.text = contentStr;
    
    [self.view addSubview:alert];
    
    alert.alertBlock = acBlock;
    
    return alert;
}

- (void)showSelectPhoto {
    
    /**
     *  弹出提示框
     */
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_album") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [GGPermissionsManage checkPhotosOpenPer:^{
            //初始化UIImagePickerController
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
            //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
            //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //允许编辑，即放大裁剪
            PickerImage.allowsEditing = YES;
            //自代理
            PickerImage.delegate = self;
            PickerImage.modalPresentationStyle = UIModalPresentationFullScreen;
            //页面跳转
            [self presentViewController:PickerImage animated:YES completion:nil];
        } faile:^{
            
        }];
        
    }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_camera") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        [GGPermissionsManage checkCameraPer:^{
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式:通过相机
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = YES;
            PickerImage.delegate = self;
            PickerImage.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:PickerImage animated:YES completion:nil];
        } faile:^{
            
        }];
        
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_cancel") style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showPickView {
    
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    // 2.设置属性
    datePickerView.backgroundColor = UIColorClear;
    datePickerView.pickerMode = BRDatePickerModeYMD;
    datePickerView.showUnitType = BRShowUnitTypeNone;
//    datePickerView.shortMonthName = YES;
//    datePickerView.monthNameType = BRMonthNameTypeNumber;
    datePickerView.title = @"DD/MM/YYYY";
    
    datePickerView.minDate = [NSDate br_setYear:1900 month:1 day:1];
    datePickerView.maxDate = [NSDate date];
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"];
//    if ([language isEqualToString:@"vi"]) {
//        /*
//         háng Một (Giêng), 二月Tháng Hai,三月Tháng Ba,四月Tháng Tư,五月Tháng Năm,六月Tháng Sáu,七月Tháng Bảy,八月Tháng Tám,九月Tháng Chín,十月Tháng Mười,十一月Tháng MườiMột,十二月Tháng Mười Hai
//         */
//       NSArray *moonArr = @[@"háng Một",@"Tháng Hai",@"Tháng Ba",@"Tháng Tư",@"Tháng Năm",@"Tháng Sáu",@"Tháng Bảy",@"Tháng Tám",@"Tháng Chín",@"Tháng Mười",@"Tháng MườiMột",@"Tháng Mười Hai"];
    NSArray *mothArr = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    datePickerView.monthNames = mothArr;

    NSString *str = USERManager.userModel.birthday;
//    str = (str.length != 0) ? str : @"DD/MM/YYYY";
    if (str.length != 0) {
        datePickerView.selectDate = [self br_dateOfStr:str];
    }else {
        datePickerView.selectDate = [NSDate date];
    }
   
    
    WS(weakSelf);
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        
        if (selectValue.length != 0) {
            NSArray *days = [selectValue componentsSeparatedByString:@"-"];
            if (days.count == 3) {
                
                days  = [[days reverseObjectEnumerator] allObjects];
                
                NSString *dateString = [days componentsJoinedByString:@"/"];
                
                NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:[weakSelf infoDefaultDic]];
                
                dic[@"birthday"] = dateString;
                
                [weakSelf changeInfo:dic succ:^{
                    
                } faile:^{
                    
                }];
                
                return;
            }
        }
            
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy"];
        
        NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"appLanguage"];
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
        [formatter setLocale:locale];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSString *zoneAbbreviation = [zone abbreviation];
        NSString *gmtStr = zoneAbbreviation;
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:gmtStr];
        [formatter setTimeZone:timeZone];
            
        NSString *dateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:selectDate]];
        
//        weakSelf.userModel.birthday = dateString;
//        [weakSelf.tableView reloadData];
        NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:[weakSelf infoDefaultDic]];
        
        dic[@"birthday"] = dateString;
        
        [weakSelf changeInfo:dic succ:^{
            
        } faile:^{
            
        }];
        
        
    };
    // 设置自定义样式
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.language = language;
    customStyle.topCornerRadius = 20;
    customStyle.hiddenShadowLine = YES;
    customStyle.alertViewColor = UIColor.qd_backgroundColor2;
    
    customStyle.titleBarHeight = 60;
    customStyle.hiddenTitleLine = YES;
    customStyle.titleTextColor = UIColor.qd_titleTextColor;
    customStyle.titleTextFont = [UIFont br_fontB:17];
    customStyle.titleLabelFrame = CGRectMake(80, 10, kScreenWidth-160, 50);
    
    customStyle.selectRowColor = UIColor.qd_backgroundColor2;
    customStyle.selectRowTextFont = [UIFont br_fontB:17];
    customStyle.selectRowTextColor = kColorMain;
    
    customStyle.cancelTextColor = UIColor.qd_placeholderColor;
    customStyle.cancelTextFont = [UIFont br_fontM:14];
    customStyle.cancelBtnTitle = Localized(@"public_cancel");
    customStyle.cancelBtnFrame = CGRectMake(10, 10, 80, 50); // 因为荷兰语 宽度从70-》80
    customStyle.doneTextColor = kColorMain;
    customStyle.doneTextFont = [UIFont br_fontM:14];
    customStyle.doneBtnTitle = Localized(@"profile_confirm");
    customStyle.doneBtnFrame = CGRectMake(kScreenWidth-90, 10, 80, 50);
    customStyle.titleBarColor = UIColor.qd_backgroundColor2;
    customStyle.titleLineColor = UIColor.qd_lineColor2;
    customStyle.pickerColor = UIColor.qd_backgroundColor2;
    customStyle.pickerTextColor = UIColor.qd_mainTextColor;
    customStyle.pickerTextFont = [UIFont br_fontM:14];
    customStyle.separatorColor = UIColor.qd_backgroundColor2;
    datePickerView.pickerStyle = customStyle;

    // 3.显示
    [datePickerView show];
}

- (NSDate *)br_dateOfStr:(NSString *)time {
    
    if (![time containsString:@"/"]) {
        return [NSDate date];
    }
    NSArray *arr = [time componentsSeparatedByString:@"/"];
    
    if (arr.count != 3) {
        return [NSDate date];
    }
    
    NSInteger year = [arr[2] integerValue];
    NSInteger month = [arr[1] integerValue];
    NSInteger day = [arr[0] integerValue];
    
    return [NSDate br_setYear:year month:month day:day];
}


#pragma mark - UINavigationControllerDelegate, UIImagePickerControllerDelegate
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    // 压缩需要上传的图片
    UIImage *uploadImage = [self imageWithImageSimple:newPhoto scaledToSize:CGSizeMake(255, 255)];
    NSData *uploadData = UIImageJPEGRepresentation(uploadImage, 1);;
    [self uploadHeader: uploadData];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadHeader:(NSData*)data{
    
    [BRHud showHud];
    WS(weakSelf);
    [BRAPI uploadFiles:data beginBlock:^{

    } successBlock:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:[weakSelf infoDefaultDic]];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code != 0) {
            [BRHud hidden];
            NSLog(@"%@",responseObject[@"message"])
            return;
        }

        dic[@"icon"] = responseObject[@"data"][@"value"];

        [[BRRequestManager shared] PUT:[BRAPI editUserInfo] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {


            // 使用新接口获取最新用户信息
            [BRUserManager requestUserCenterInfo:^{
                [self.tableView reloadData];
                [BRHud hidden];
            } faile:^{
                // 新接口失败，提示错误
                [BRHud hidden];
                [BRHud showTips:@"获取用户信息失败"];
            }];

        } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
            [BRHud hidden];
        }];

    } failureBlock:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BRHud hidden];
    }];
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

#pragma mark - SET UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"profile_profile")];
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColorClear;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRTopTitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRTopTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRHeaderImgTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRHeaderImgTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRTitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRTitleTableViewCell"];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    head.backgroundColor = UIColor.clearColor;
    self.tableView.tableHeaderView = head;
    
}

- (NSArray *)lists {
    //@"headerImg",
    // TODO: 屏蔽邮箱和接收数据邮箱，新增昵称项
    return @[Localized(@"menu_userID"),
             @"nickName",  // 昵称（使用固定字符串作为key，显示时使用Localized(@"profile_nickName")）
             Localized(@"login_phoeNumber")
             /* 屏蔽邮箱相关
             Localized(@"login_email"),
             Localized(@"profile_receiptEmail")
             */
             ];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
